//
//  MBWebViewController.m
//  bp
//
//  Created by TeemoYang on 2023/7/14.
//

#import "MBWebViewController.h"
#import "MBCustomNavView.h"
#import "NSObject+ViewController.h"
#import <WebKit/WebKit.h>

@interface MBWebViewController ()
<
WKNavigationDelegate,
WKScriptMessageHandler
>
@property(nonatomic,strong) MBCustomNavView *navView;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, assign) BOOL isLogoutSuccess;

@end

@implementation MBWebViewController
#pragma mark - Public Metohd
- (void)loadWithURL:(NSURL *)url {
    if (url == nil) {
        return;
    }
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
    [self.webView loadRequest:urlRequest];
    /* // 或者使用如下方式
     NSString *localHtmlStr = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"QiLink" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
     [_webView loadHTMLString:localHtmlStr baseURL:[[NSBundle mainBundle] bundleURL]];
     */
    
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"JSCallIOS" ofType:@"html"];
//    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
//    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
}

- (void)setTitleStr:(NSString *)titleStr {
    _titleStr = titleStr;
    self.navView.titleLab.text = titleStr;
}


#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isLogoutSuccess = NO;
    [self setupUI];
    // Add a script message handler named "nativeHandler"
    [self addPhoneCallForJS];
    [self addPopVCForJS];
    [self addPopToRootVCForJS];
    [self addLogoutSucceededForJS];
    [self addNativeHandlerForJS];
}

- (void)dealloc {
    // Remove the script message handler to break the retain cycle
    [self removeAllMethodForJS];
    self.webView.navigationDelegate = nil;
}

- (BOOL)hbd_backInteractive {
    if (self.isLogoutSuccess) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        double delayInSeconds = 0.1;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            // 要延时执行的代码
            UIViewController *tmpCurrentVC = self.currentViewController;
            tmpCurrentVC.tabBarController.selectedIndex = 0;
        });
        return NO;
    }
    
    if (self.webView.canGoBack) {
        [self.webView goBack];
        return NO;
    }
    return YES;
}

#pragma mark - Private Method
- (void)addNativeHandlerForJS {
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"nativeHandler"];
}

- (void)addPhoneCallForJS {
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"makePhoneCall"];
}

- (void)addPopVCForJS {
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"goHome"];
}

- (void)addPopToRootVCForJS {
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"goPersonalCenter"];
}

- (void)addLogoutSucceededForJS {
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"logout"];
}

- (void)removeAllMethodForJS {
    if (@available(iOS 14.0, *)) {
        [self.webView.configuration.userContentController removeAllScriptMessageHandlers];
    } else {
        // Fallback on earlier versions
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeHandler"];
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"makePhoneCall"];
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goHome"];
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"goPersonalCenter"];
    }
}

- (void)makePhoneCall:(NSString *)phoneNumber {
    phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    NSString *phoneURLString = [NSString stringWithFormat:@"tel:%@", phoneNumber];
    NSURL *phoneURL = [NSURL URLWithString:phoneURLString];
    
    if ([[UIApplication sharedApplication] canOpenURL:phoneURL]) {
        [[UIApplication sharedApplication] openURL:phoneURL options:@{} completionHandler:nil];
    } else {
        // Handle the case where the device can't make phone calls (e.g., simulator).
        // You may want to display an alert to inform the user that the call cannot be made.
    }
}

#pragma mark - Delegate
#pragma mark WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // The webpage has finished loading
    if (self.title == nil) {
        self.title = webView.title;
    }
}

#pragma mark WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // Handle the message received from JavaScript
    if ([message.name isEqualToString:@"makePhoneCall"]) {
        // The message.body contains the data passed from JavaScript
        NSString *phoneNumber = message.body;
        [self makePhoneCall:phoneNumber];
    } else if ([message.name isEqualToString:@"goHome"]) {
        // The message.body contains the data passed from JavaScript
        [self.navigationController popToRootViewControllerAnimated:YES];
        double delayInSeconds = 0.1;
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            // 要延时执行的代码
            UIViewController *tmpCurrentVC = self.currentViewController;
            tmpCurrentVC.tabBarController.selectedIndex = 0;
        });
    } else if ([message.name isEqualToString:@"goPersonalCenter"]) {
        // The message.body contains the data passed from JavaScript
        NSString *dataFromJS = message.body;
        NSLog(@"Data from JavaScript: %@", dataFromJS);
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else if ([message.name isEqualToString:@"logout"]) {
//        NSString *dataFromJS = message.body;
//        if ([dataFromJS isEqualToString:@"true"]) {
//            [HEMSUserLoginInfoModel deleteDoc];
//            self.isLogoutSuccess = YES;
//        }
    }
}

#pragma mark - UI
- (void)setupUI {
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(StatusBarAndNavigationBarHeight);
        make.left.right.bottom.equalTo(self.view);
    }];
}

#pragma mark - Setter && Getter
- (WKWebView *)webView {
    if (!_webView) {
        WKUserContentController *contentContrller = [[WKUserContentController alloc] init];
        WKWebViewConfiguration *webConfig = [WKWebViewConfiguration new];
        webConfig.dataDetectorTypes = WKDataDetectorTypePhoneNumber;
        webConfig.userContentController = contentContrller;
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfig];
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.navigationDelegate = self;
    }
    return _webView;
}

- (MBCustomNavView *)navView {
    if (!_navView) {
        _navView = [MBCustomNavView new];
    }
    return _navView;
}

@end
